// 传过来的参数
var selectorParams = JSON.parse(sessionStorage.getItem ('selectEsysMenuParams'));
// 存放用户选择的角色数据
var selectedData = {};
// 初始化已经选择的数据
var idField = $('#' + selectorParams.formId + ' input[name=' + selectorParams.idField + ']');
var nameField = $('#' + selectorParams.formId + ' span[name=' + selectorParams.nameField + ']');
selectedData.id = idField.val().split(',');
selectedData.name = nameField.text().split(',');
console.log ('selectedData', selectedData);
// 滤除空字符串
if (!selectedData.id[0]) {
	selectedData.id = [];
	selectedData.name = [];
}

// 为datagrid增加onBeforeLoad事件
$('#dgEsysMenuSelector').datagrid({
	idField : 'id',
	onLoadSuccess : function (data) {
		console.log ('data', data);
		for (var i = 0; i < selectedData.id.length; i ++) {
			$(this).datagrid('selectRecord', selectedData.id[i]);
		}
	},
	onBeforeLoad : function (param) {// onBeforeLoad在datagrid请求列表数据之前被调用，param是请求的参数对象
		var t = $('#fm-searchEsysMenuSelector').serializeArray();
        $.each(t, function() {
        	if (this.value != '' && this.value != undefined) {
        		// 使用form中的name和value设置param属性值
        		param[this.name] = this.value;
        	}
        });
        return true;
	},
	onClickRow : function (rowIndex, rowData) {
		// 单选
		if (selectorParams.singleSelect) {
			selectedData.id = [rowData.id.toString()];
    		selectedData.name = [rowData.name.toString()];
    		return;
		}
		// 多选
		var index = -1;
    	for (var i = 0; i < selectedData.id.length; i ++) {
    		var id = selectedData.id[i];
    		if (id == rowData.id) {
    			index = i;
    			break;
    		}
    	}
    	// 添加或者删除元素
    	if (index == -1) {
    		// 添加元素
    		selectedData.id.push(rowData.id.toString());
    		selectedData.name.push(rowData.name.toString());
    	} else {
    		// 删除元素
    		selectedData.id.splice(index, 1);
    		selectedData.name.splice(index, 1);
    	}
    	console.log (selectedData);
	},
	singleSelect : selectorParams.singleSelect
});

// 查询按钮点击事件
$('#fm-searchEsysMenuSelector input[buttonIcon=icon-search]').textbox({
	onClickButton : function () {
		$('#dgEsysMenuSelector').datagrid('reload');
	}
});

// 确定按钮点击事件
$('#dlg-buttons-selectEsysMenu a:first').click (function () {
	// 保存选中数据
	idField.val(selectedData.id.join(','));
	nameField.text(selectedData.name.join(','));
	$('#dlg-selectEsysMenu').dialog('close'); // close the dialog
});

// 取消按钮点击事件
$('#dlg-buttons-selectEsysMenu a:last').click (function () {
	$('#dlg-selectEsysMenu').dialog('close'); // close the dialog
});